package main

import (
	"database/sql"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"log"
)

func main() {
	fmt.Println("---mysql---")
	var db *sql.DB

	//1 开启 mysql db
	if db = OpenMysql(); db != nil {
		fmt.Println("open successful!")
	}

	//关闭
	defer db.Close()

	fmt.Println(db == nil)

	//2 删除 创建table
	createUserTable(db)

	//3

}

//
func createUserTable(db *sql.DB) {
	dropSql := `
		drop table if exists user;
	`
	_, err := db.Exec(dropSql)
	if err != nil {
		log.Fatal(err)
	}

	createSql := `
		create table user (
			id INT AUTO_INCREMENT,
			username TEXT NOT NULL,
			password TEXT NOT NULL,
			created_at DATETIME,
			PRIMARY KEY (id)
		)
	`
	result, err := db.Exec(createSql)
	if err != nil {
		log.Fatal(err)
	}

	id, _ := result.LastInsertId()
	affected, _ := result.RowsAffected()

	fmt.Println("LastInsertId", id)
	fmt.Println("RowsAffected", affected)
}

//
func OpenMysql() *sql.DB {
	//打开
	db, err := sql.Open("mysql", "admin:admin@(localhost:3306)/example?parseTime=true")
	if err != nil {
		log.Fatal(err)
		return nil
	}
	//测试通断
	err = db.Ping()
	if err != nil {
		log.Fatal(err)
		return nil
	}
	return db
}
